<template><!---->
    <div id="test">
        <search-table
            :columns="listCol"
            :data="retData.list"
            :total="retData.total"
            :page.sync="queryParams.pageIndex"
            :size.sync="queryParams.pageSize"
            @queryFun="getRankingStatic">
            <template slot="select-group">
                <Select filterable
                    v-model="queryParams.teamId"
                    placeholder="请选择团队"
                    filterable
                    clearable
                    transfer
                    @on-change="getRankingStatic(1)">
                    <Option  v-for="item in teamList" :value="item.id"  :key="item.id" :title="item.name">{{item.name}}</Option>
                </Select>
                <Select filterable
                    v-model="queryParams.target"
                    placeholder="请选择目标"
                    filterable
                    clearable
                    transfer
                    @on-change="getRankingStatic(1)">
                    <Option  v-for="item in topoTargetData" :value="item.id"  :key="item.id" :title="item.company">{{item.company}}</Option>
                </Select>
                <Select filterable v-model="queryParams.type" filterable placeholder="请选择报告类型" clearable @on-change="getRankingStatic(1)">
                    <Option :value="1">攻击报告</Option>
                    <Option :value="2">防御报告</Option>
                </Select>
                <Select filterable transfer v-model="queryParams.publicTarget" placeholder="是否公共目标" filterable clearable 
                    @on-change="getRankingStatic(1)">
                    <Option value="1">是</Option>
                    <Option value="0">否</Option>
                </Select>
                <Select filterable
                    v-model="queryParams.industry"
                    placeholder="请选择行业"
                    filterable
                    clearable
                    @on-change="getRankingStatic(1)">
                    <Option  v-for="item in industryList" :value="item.dictid"  :key="item.dictid" :title="item.dictname">{{item.dictname}}</Option>
                </Select>
                <Select filterable
                    v-model="queryParams.attackType"
                    placeholder="请选择攻击类型"
                    filterable
                    clearable
                    @on-change="getRankingStatic(1)">
                    <Option  v-for="item in attackList" :value="item.dictid"  :key="item.dictid" :title="item.dictname">{{item.dictname}}</Option>
                </Select>
                <Cascader :render-format="renderFormat" transfer :data="extent4DefenseTypesData" v-model="queryParams.defenseTypes" placeholder="请选择防守类型" 
                        filterable clearable @on-change="getRankingStatic(1)"></Cascader>
                <Cascader :render-format="renderFormat" transfer :data="extent4InjuryData" v-model="queryParams.attackLevel" placeholder="请选择危害程度" 
                        filterable clearable @on-change="getRankingStatic(1)"></Cascader>
                <Select filterable
                    v-model="queryParams.level"
                    placeholder="请选择危险等级"
                    filterable
                    clearable
                    @on-change="getRankingStatic(1)">
                    <Option value="high">高危</Option>
                    <Option value="middle">中危</Option>
                    <Option value="low">低危</Option>
                </Select>
                <Select filterable
                    v-model="queryParams.isverify"
                    placeholder="请选择审核状态"
                    filterable
                    clearable
                    @on-change="getRankingStatic(1)">
                    <Option value="1">未审核</Option>
                    <Option value="2">审核通过</Option>
                    <Option value="3">驳回</Option>
                </Select>
            </template>
        </search-table>
        <!-- <card-list
            slot="table"
            :columns="listCol"
            :data="retData.list"></card-list> -->
        <!-- <table-body :options="initObj"></table-body> -->
        <Modal v-model="reportModal"
            :title="modalTitle"
            width="800px"
            :mask-closable = "false"
            footer-hide
            >
            <table-body :options="reportInitObj" v-if="reportModal" :hidePage="true" noDataText="暂无报告"></table-body>
        </Modal>
    </div>
</template>
<script>
//	import Cookies from 'js-cookie'
import {reportStatis,downloadFile} from '@/api/compitionStatic'
import {reportFileData} from '@/api/referee'
import { allDirection } from '@/api/dict'
import tableBody from './tableListComponent'
import groupMixin from "@/mixin/groupMixin";
import LevelMixin from '@/mixin/levelMixin'
import {getTopoTargetList_old} from '@/api/drill_compete'
import SearchTable from '@/components/SearchTable/SearchTable'
export default {
    name: 'hwTeamRankStatic',
    props:['sceneId','poll'],
    mixins: [groupMixin, LevelMixin],
    data(){
        const d = function(val){
            this.getRankingStatic(null,null,val)
        }.bind(this);

        return {
            queryParams: {
                teamId: '',
                target: '',
                industry: '',
                attackType: '',
                level: '',
                isverify: '',
                defenseTypes: [],
                attackLevel: [],
                publicTarget: '',
                pageIndex: 1,
                type: '',
                pageSize: 10
            },
            retData: {
                total: 0,
                list: []
            },
            modalTitle: '',
            topoTargetData: [],
            reportModal:false,
            c:false,
            listCol:[
                {
                title:'团队名称',
                key:'groupName',
                align:'center',
                ellipsis:true,
                tooltip:true,
                placement:'top-left',
                order:1
                },
                {
                title:'题目显示名称',
                key:'targetName',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100,
                placement:'top-left',
                },
                {
                title:'任务名称',
                key:'taskName',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100,
                },
                {
                title:'报告',
                key:'reportName',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100,
                },
                {
                title:'行业',
                key:'industryName',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100,
                },
                {
                title:'攻击类型',
                key:'attackTypeName',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100,
                },
                {
                    title:'防守类型',
                    key:'defenseTypeName',
                    width:100,
                    tooltip:true,
                },
                // {
                // title:'状态', //1提交，2审批通过，3审批不通过
                // key:'status',
                // align:'center',
                // ellipsis:true,
                // tooltip:true,
                // placement:'top-right',
                // render:(h,params) => {
                //     return h('span',params.row.status == 1 ? '提交' :params.row.status == 2 ? '审批通过' : '审批不通过')
                // }
                // },
                {
                title:'提交人',
                key:'creatorName',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100,
                },
                {
                title:'提交时间',
                key:'createTime',
                align:'center',
                ellipsis:true,
                tooltip:true
                },
            {
                title:'审核状态',
                key:'status',
                align:'center',
                ellipsis:true,
                render:(h,params)=>{
                    let obj = this.mixinPaserStatus(params.row.status)
                    return h('span', {
                        style: {
                            color: obj.color,
                            width: '60px',
                            display: 'inline-block'
                        }
                    }, obj.text)
                }
                },
                {
                title:'审批信息',
                key:'approvalInfo',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100,
                },
                {
                    title:'危险等级',
                    key:'level',
                    width:100,
                    tooltip:true,
                    render:(h,params)=>{
                        let obj = this.mixinPaserLevel(params.row.level)
                        return h('span', {
                            style: {
                                color: obj.color,
                            }
                        }, obj.text)
                    }
                },
                {
                    title:'危害程度',
                    key:'attackLevelName',
                    align:'center',
                    width:150,
                    tooltip: true
                },
                {
                    title: '防守方扣分',
                    key:'score1',
                    align:'center',
                    width:80,
                    tooltip: true,
                    render:(h,params)=>{
                        return h('span', params.row.type !== 2 && (params.row.score || params.row.score === 0) ? params.row.score : '无')
                    }
                },
                {
                    title: '防守方得分',
                    key:'score2',
                    align:'center',
                    width:80,
                    tooltip: true,
                    render:(h,params)=>{
                        return h('span', params.row.type === 2 && (params.row.score || params.row.score === 0) ? params.row.score : '无')
                    }
                },
                {
                title:'审批人',
                key:'userName',
                align:'center',
                ellipsis:true,
                tooltip:true,
                width:100,
                },
                {
                title:'审批时间',
                key:'approvalTime',
                align:'center',
                ellipsis:true,
                tooltip:true
                },
                {
                    title:'操作',
                    align:'center',
                    placement:'top-right',
                    key:'action',
                    width:160,
                    fixed:'right',
                    opList:[
                        {
                            txt:'防御报告',
                            show:(data) => data.type === 1,
                            on:{
                                click:(data)=>{
                                    this.getFileList(data, 0); // 展示关联的防御报告
                                }
                            }
                        },
                        {
                            txt:(data) => data.type === 1 ? '攻击报告' : '防御报告',
                            on:{
                                click:(data)=>{
                                    this.getFileList(data, 1); // 展示当前报告
                                }
                            }
                        }
                    ],
                    // render:(h,params) => {
                    //     return h('div',{
                    //         style: {
                    //             width: '150px'
                    //         }
                    //     },[
                    //         h('Button',{
                    //             props:{
                    //                 type:'primary',
                    //                 size:'small',
                    //             },
                    //             style:{
                    //                 marginRight:'5px',
                    //                 display: params.row.type === 1 ? 'inline-block' : 'none',
                    //             },
                    //             on:{
                    //                 click:()=>{
                    //                     this.getFileList(params.row, 0); // 展示关联的防御报告
                    //                 }
                    //             }
                    //         },'防御报告'),
                    //         h('Button',{
                    //             props:{
                    //                 type:'primary',
                    //                 size:'small',
                    //             },
                    //             style:{
                    //                 marginRight:'5px',
                    //             },
                    //             on:{
                    //                 click:()=>{
                    //                     this.getFileList(params.row, 1); // 展示当前报告
                    //                 }
                    //             }
                    //         }, params.row.type === 1 ? '攻击报告' : '防御报告')
                    //     ])
                    // }
                },
            ],
            reportInitObj:{
                loading:false,
                showLoading:false,
                Button:[],
                Input:[],
                Select:[],
                DatePicker:{
                isShow:false,
                fnName:d,
                },
                Page:{
                total:0,
                currentPage:1,
                pageSize:10
                },
                Table:{
                    listCol:[
                        {
                        title:'名称',
                        key:'name',
                        align:'center',
                        ellipsis:true,
                        tooltip:true,
                        placement:'top-left',
                            width: 240
                        },
                        {
                        title:'提交人',
                        key:'creatorName',
                        align:'center',
                        ellipsis:true,
                        tooltip:true,
                            width:120
                        },
                        {
                            title:'操作',
                            align:'center',
                            key: 'active1',
                            placement:'top-right',
                            action:true,
                            render:(h,params) => {
                                return h('Button',{
                                props:{
                                    type:'primary',
                                    size:'small',
                                },
                                style:{
                                    marginRight:'5px',
                                },
                                on:{
                                    click:()=>{
                                        //this.downloadFile(params.row);
                                    }
                                }
                                },[
                                    h('a',{
                                        attrs:{
                                            href:`/api/minio/download/${params.row.id}`
                                        },
                                        style:{
                                            color:'#fff'
                                        }
                                    },'下载')
                                ])
                            }
                        }
                    ]
                },
                listData:[]
            },
            timeout:{},
            industryList: [],
            attackList: [],
            extent4InjuryData: [],
            extent4DefenseTypesData: [],
        }
    },
    computed: {
        filterTeamList() {
            return this.teamList.filter(item => item.name !== '目标方管理员组')
        }
    },
    components:{
        'table-body':tableBody,
        SearchTable
    },
    watch:{
    },
    created(){
    },
    beforeDestroy(){
        clearTimeout(this.timeout)
    },
    async mounted(){
        await this.getIndustryTypes()
        await this.getAttackTypes()
        await this.getHwAttackLevelTypes()
        await this.getHwDefenseTypes()
        this.getRankingStatic();
        this.getTopoTargetList()
    },
    methods:{
        // 级联选择只展示叶子节点的内容
        renderFormat(label) {
            return label[label.length - 1]
        },
        // 获取目标危害程度
        getHwAttackLevelTypes() {
            return new Promise(resolve => {
                allDirection({ dictTypeID: 'hwAttackLevelTypes' }).then(({ code, message, attribute = {} }) => {
                    attribute = attribute.attribute || []
                    if (code !== 1) {
                    this.$Message.warning(message)
                    return
                    }
                    let list = []
                    attribute.forEach(item => list = list.concat(item.dictEntryList))
                    this.attackLevelList = list
                    let parentNodeList = list.filter(item => item.parentid === '')
                    this.extent4InjuryData = parentNodeList.map(item => {
                    let ret = {
                        value: item.dictid,
                        label: item.dictname,
                        children: []
                    }
                    list.forEach(subItem => {
                        if (subItem.parentid === item.dictid) { // 将二级的字典遍历查询出来
                        ret.children.push({
                            value: subItem.dictid,
                            label: subItem.dictname
                        })
                        }
                    })
                    return ret
                    })
                }).catch(() => {
                    this.$Message.error('获取目标危害程度列表异常')
                }).finally(() => {
                    resolve()
                })
            })
        },
        // 获取目标危害程度
        getHwDefenseTypes() {
            return new Promise(resolve => {
                allDirection({ dictTypeID: 'hwDefenseTypes' }).then(({ code, message, attribute = {} }) => {
                    attribute = attribute.attribute || []
                    if (code !== 1) {
                        this.$Message.warning(message)
                        return
                    }
                    let list = []
                    attribute.forEach(item => list = list.concat(item.dictEntryList))
                    this.defenseTypesList = list
                    let parentNodeList = list.filter(item => item.parentid === '')
                    this.extent4DefenseTypesData = parentNodeList.map(item => {
                        let ret = {
                            value: item.dictid,
                            label: item.dictname,
                            children: []
                        }
                        list.forEach(subItem => {
                            if (subItem.parentid === item.dictid) { // 将二级的字典遍历查询出来
                            ret.children.push({
                                value: subItem.dictid,
                                label: subItem.dictname
                            })
                            }
                        })
                        return ret
                    })
                }).catch(() => {
                    this.$Message.error('获取目标危害程度列表异常')
                }).finally(() => {
                    resolve()
                })
            })
        },
        // 获取行列列表
        getIndustryTypes() {
            return new Promise(resolve => {
            allDirection({ dictTypeID: 'hwIndustryTypes' }).then(({ code, message, attribute = {} }) => {
                attribute = attribute.attribute || []
                if (code !== 1) {
                this.$Message.warning(message)
                return
                }
                let list = []
                attribute.forEach(item => list = list.concat(item.dictEntryList))
                this.industryList = list
            }).catch(() => {
                this.$Message.error('获取行业列表异常')
            }).finally(() => {
                resolve()
            })
            })
        },
        // 获取攻击类型列表
        getAttackTypes() {
            return new Promise(resolve => {
            allDirection({ dictTypeID: 'hwAttackTypes' }).then(({ code, message, attribute = {} }) => {
                attribute = attribute.attribute || []
                if (code !== 1) {
                this.$Message.warning(message)
                return
                }
                let list = []
                attribute.forEach(item => list = list.concat(item.dictEntryList))
                this.attackList = list
            }).catch(() => {
                this.$Message.error('获取攻击类型列表异常')
            }).finally(() => {
                resolve()
            })
            })
        },
        getTopoTargetList(){
            getTopoTargetList_old({
                pageIndex:1,
                pageSize:2147483647,
                projectId:this.$route.query.prjid
            }).then(data => {
                if(data.code==1){
                    this.topoTargetData = data.data.items || data.data;
                }else{
                    this.topoTargetData = []
                    this.$Message.warning(data.message);
                }
            })
        },
        getRankingStatic(page){
            this.$nextTick(() => {
                page !== undefined && (this.queryParams.pageIndex = page) // page不为空时，将page赋值给pageIndex
                let {
                    teamId,
                    target,
                    industry,
                    attackType,
                    level,
                    isverify,
                    pageIndex,
                    pageSize,
                    type,
                    defenseTypes,
                    publicTarget,
                    attackLevel,
                } = (this.queryParams || {})
                let params={
                    page: pageIndex,
                    pageSize,
                    testId: this.$route.query.id,
                    industry,
                    attackType,
                    level,
                    status: isverify,
                    target,
                    groupId: teamId,
                    type,
                    defenseType: defenseTypes.length ? defenseTypes[defenseTypes.length - 1] : undefined,
                    publicTarget: publicTarget ? publicTarget === '1' : undefined,
                    attackLevel: attackLevel.length ? attackLevel[attackLevel.length - 1] : undefined,
                };
                if(this.$route.query.id){
                    reportStatis(params).then(data=>{
                    if(data.code==1){
                        let list = data.data.pageData
                        this.retData.list = list.map(item => {
                            item.attackTypeName = this.getValueByList(item.attackType, this.attackList)
                            item.industryName = this.getValueByList(item.industry, this.industryList)
                            item.attackLevelName = this.getValueName(item.attackLevel, this.attackLevelList)
                            item.defenseTypeName = this.getValueName(item.defenseType, this.defenseTypesList)
                            return item
                        })
                        this.retData.total = data.data.totalCount;
                        if(this.poll){ //如果需要轮询
                            clearTimeout(this.timeout)
                            this.timeout = setTimeout(() => {
                                this.getRankingStatic(page);
                            },10000)
                        }
                    }
                    })
                }
            })
        },
        // 递归获取级联选择框的数据
        getValueName(value, operatedList, list = []) {
            let item = (operatedList.find(item => item.dictid === value) || {})
            list.unshift(item.dictname)
            if (item.parentid) {
                this.getValueName(item.parentid, operatedList, list)
            }
            return list.join(' / ')
        },
        // 从列表中找出对应ID的名称，无法获取时返回ID
        getValueByList(id, list) {
            let item = list.find(item => item.dictid === id)
            return item ? item.dictname : id
        },
        // 将行业Id转换为对应的名称
        getIndustryName(industryId) {
            let item = this.industryList.find(item => item.dictid === industryId)
            // 返回对应的名称，没有查到数据，还是返回ID
            return item ? item.dictname : industryId
        },
        getFileList(item, type){
            let _this = this;
            this.fileModal = true
            this.defeFileList = []
            reportFileData(item.id)
                .then(res=>{
                    if(res.data.code === 1){
                        let attackStartTime = res.data.data.startTime;
                        let attackEndTime = res.data.data.endTime;
                        let reportName = res.data.data.reportName
                        let defeFileList = res.data.data.defenseFiles // 防御报告
                        let fileList = res.data.data.files // 攻击报告
                        if (type === 0) {
                            _this.reportInitObj.Table.listData = defeFileList
                            this.modalTitle = '防御报告'
                        } else {
                            _this.reportInitObj.Table.listData = fileList
                            this.modalTitle = item.type === 1 ? '攻击报告' : '防御报告'
                        }
                        let connectRecords = res.data.data.connectRecords
                        this.reportModal = true;
                        _this.reportInitObj.loading = false
                    }
                })
                .catch(err=>{
                    _this.reportInitObj.loading = false
                    console.log(err)
                })
        },
        downloadFile(file){
            downloadFile(file.id).then(data => {
                if(!data.code){
                    const downloadElement = document.createElement("a");
                    const href = window.URL.createObjectURL(data);
                    downloadElement.href = href;
                    downloadElement.download = file.name;
                    document.body.appendChild(downloadElement);
                    downloadElement.click();
                    document.body.removeChild(downloadElement); // 下载完成移除元素
                    window.URL.revokeObjectURL(href); // 释放掉blob对象
                }else{
                    this.$Message.error(data.message);
                }
            }).catch(error => {
                this.$Message.error('下载报告失败!');
            })
        },
    },
}
</script>

<style>
.drillsTable .ivu-poptip-body {
    text-align: left!important;
}
.scenesHeader{
    margin-bottom: 16px;
}
.drillTables{
    min-height: 300px;
}
.drillsTable.ivu-table-wrapper{
    overflow: inherit;
}
</style>
<style scoped>
.Titles{
    background: #eeeeee;
    margin: 16px auto;
    padding: 10px 0;
}
.targetHeader{
    padding: 10px;
    margin-bottom: 10px;
}
</style>
